/**
 * 
 */
package net.frankish.moviebank2.front;

import java.awt.BorderLayout;
import java.awt.RenderingHints;
import java.awt.image.RenderedImage;
import java.util.logging.Logger;

import javax.media.jai.JAI;
import javax.media.jai.operator.ScaleDescriptor;
import javax.swing.JPanel;

import net.frankish.moviebank.util.Configs;
import net.frankish.tools.GuiTools;

import com.sun.media.jai.widget.DisplayJAI;

class PictureRendererThread implements Runnable{
	private static final Logger logger = Logger.getLogger(PictureRendererThread.class.getName());
	private JPanel destination = null;
	private String fileName = null;
	private byte[] imageRaw = null;

	PictureRendererThread(String fileName, byte[] imageRaw, JPanel destination){
		this.destination = destination;
		this.fileName = fileName;
		this.imageRaw = imageRaw;
	}
	
	public void run() {
		logger.finest("Loading coverpicture. Filename["+fileName+"] RawImageBytes["+(imageRaw != null ? imageRaw.length:"(null)")+"] Destination["+destination+"]");
	try{
		if(fileName != null) {
			RenderedImage img = JAI.create("fileload", Configs.getInstance().getProperty("InstallFolder",".") + "/images/"+fileName);
			int width = img.getWidth(), height = img.getHeight(), largestPicture = 0, largestContainer = 0;
			if(width > height){
				largestPicture = width;
				largestContainer = destination.getWidth()-10;
			}
			else{
				largestPicture = height;
				largestContainer = destination.getHeight()-10;
			}

			float ratio = ((float)largestContainer) / ((float)largestPicture);
			RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
			hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON));
			hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC));
			img = ScaleDescriptor.create(img,new Float(ratio),new Float(ratio*0.95),new Float(0),new Float(0),null,hints);
			DisplayJAI pane = new DisplayJAI(img);
			pane.setToolTipText("File: "+fileName);
			GuiTools.setSizes(pane, img.getWidth(),img.getHeight());
			destination.add(pane,BorderLayout.CENTER);
			destination.revalidate();
		}
		destination.repaint();
	}catch(Exception ex){
		System.err.println("Image thread interupted");
		ex.printStackTrace();
	}
}
	


}